use diesel::prelude::*;

mod schema {
    diesel::table! {
        user (id) {
            id -> Int4,
            name -> Varchar,
            age -> Int4
        }
    }
}

#[derive(Queryable, Selectable, PartialEq, Debug)]
#[diesel(table_name = schema::user)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub age: i32,
}

use std::any::Any;
use schema::user::dsl;

fn has_same_type(t1: &dyn Any, t2: &dyn Any)  {
    println!("{:?}", t1.type_id());
    println!("{:?}", t2.type_id());
}

pub fn main() {
    let mut connection = establish_connection();

    let name = Some("yq".to_string());

    let mut conditions = dsl::user.into_boxed();
   conditions=conditions.filter(dsl::id.gt(2));

    if let Some(name_)=name{
       conditions = conditions.filter(dsl::name.like(format!("%{}%",name_))); 
    }   

    let results = conditions
        .limit(5)
        .select(User::as_select())
        .load(&mut connection)
        .expect("Error loading users");

    //把上面改成这样就能编译运行
    // let results = dsl::user
    //     .filter(dsl::id.gt(2))
    //     .filter(dsl::name.like("%y%"))
    //     .limit(5)
    //     .select(User::as_select())
    //     .load(&mut connection)
    //     .expect("Error loading users");

    for user in results {
        println!("use.id:{}", user.id);
        println!("user.name:{}", user.name);
        println!("user.age:{}", user.age);
        println!("-----------\n");
    }
}

pub fn establish_connection() -> MysqlConnection {
    let database_url = "mysql://root:comac.2021@localhost/diesel_practice".to_string();
    MysqlConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}

//let name: Option<String> = None;

// if let Some(name_) = name {
//     conditions = conditions.filter(dsl::name.like("22%"));
// }
